#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/14  12:55
# @Author: 余浪人
# @email: yulangren520@gmail.com

from apps.cms import cms_bp
from flask import render_template, request
from apps.lib.public import add_data, real_deletes, real_delete_data, update_status, log, edit_data, check_obj, \
    page_auto
from apps.forms.admin_form import Admin_Form, Admin_Edit_Form
from apps.models.admin_model import Admin_Model, db
from flask_login import login_required


# 管理员-列表
@cms_bp.route('/admin_list', endpoint='admin_list', methods=['GET', 'DELETE', 'DELETE_S', 'POST'])
@login_required
def admin_list():
    if request.method == 'DELETE':
        log('操作删除管理员')
        return real_delete_data(Admin_Model, db, request.form.get('uid'))
    elif request.method == 'DELETE_S':
        log('操作批量删除管理员')
        return real_deletes(Admin_Model, db, uid_s=list(eval(request.form.get('data_s') + ',')))
    elif request.method == 'POST':
        return update_status(Admin_Model, db, request.form.get('uid'), request.form.get('status'))
    data_s = Admin_Model.query.order_by(db.desc(Admin_Model.id))
    paginate, page = page_auto(data_s)
    return render_template('sys_templates/admin_member_list.html', data_s=paginate, page = page, title='管理员列表')


# 管理员-添加
@cms_bp.route('/admin_add', endpoint='admin_add', methods=['GET', 'POST'])
@login_required
def admin_add():
    if request.method == 'POST':
        log('操作添加管理员')
        return add_data(Admin_Model, Admin_Form, db)
    form = Admin_Form(request.form)
    return render_template('sys_templates/admin_member.html', form=form, title='添加管理员')


# 超级管理员-修改
@cms_bp.route('/admin_edit/<int:id>', endpoint='admin_edit', methods=['GET', 'POST'])
@login_required
def admin_edit(id):
    obj = Admin_Model.query.filter_by(id=id).first()
    if request.method == 'POST':
        return edit_data(Admin_Edit_Form, Admin_Model, db, id)
    elif not check_obj(obj):
        form = Admin_Edit_Form(data=dict(obj))
        return render_template('sys_templates/admin_member.html', form=form, title=f"编辑-{obj.username}")
